package com.cxf.windex.service.impl;

import com.cxf.windex.base.util.MapUtil;
import com.cxf.windex.base.util.XiaoBaoUtil;
import com.cxf.windex.biz.PayInfoBiz;
import com.cxf.windex.entity.PayInfo;
import com.cxf.windex.service.ProcPlanService;
import com.github.pagehelper.PageHelper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: cxf-mf
 * @description: 支付同步服务
 * @author: chenxf
 * @create: 2018-05-31 15:52
 **/
@Service
public class PayServiceImpl implements ProcPlanService {
  @Autowired
  private PayInfoBiz payInfoBiz;

  @Value("${weixin.appid}")
  private String appid;

  @Value("${xiaobao.uri}")
  private String uri;

  @Value("${xiaobao.payApi}")
  private String userApi;

  public static final Logger logger = LoggerFactory.getLogger(PayServiceImpl.class);
  /**
   * 循环处理机器人算力 直到false
   * @return
   */
  @Override
  public boolean procPlan() {
    Example example = new Example(PayInfo.class);
    Criteria criteria = example.createCriteria();
    criteria.andEqualTo("status","1");
    PageHelper.startPage(1, 1);
    List<PayInfo> items = payInfoBiz.selectByExample(example);
    if(items.size()==0){
      return false;
    }
    PayInfo payInfo=items.get(0);
    LocalDateTime d=LocalDateTime.now();
    d=d.plusYears(1);
    payInfo.setRepaytime(Date.from(d.atZone(ZoneId.systemDefault()).toInstant()));
    Map paramMap=new HashMap<String,Object>();
    try {
      paramMap.putAll( MapUtil.objectToMap(payInfo));
      paramMap.put("token",appid);
      paramMap.put("address",payInfo.getNotes());
      paramMap.remove("id");
      paramMap= XiaoBaoUtil.saveApi(paramMap,uri,userApi);
      if(paramMap.get("code").equals("0")){
        //更新状态
        payInfo.setStatus(3);
        payInfoBiz.updateSelectiveById(payInfo);
      }else{
        //同步异常
        payInfo.setStatus(4);
        payInfoBiz.updateSelectiveById(payInfo);
      }
      logger.debug("map={}",paramMap);
    } catch (Exception e) {
      e.printStackTrace();
      payInfo.setStatus(4);
      payInfoBiz.updateSelectiveById(payInfo);
    }

    return true;
  }
}
